The goals / steps of this project are the following:
FLG_DEBUG = False #True
import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline
def show_images(images):
num_img = len(images)
#print(num_img)
#plt.figure(figsize=(15,5))
#fig, axes = plt.subplots(num_img, 1)
#for axe, i in zip(axes.flat, range(num_img)):
# print(i)
# axe.imshow(images[i])
# #plt.imshow(images[i])
for i in range(num_img):
#print("i:",i)
plt.figure(i)
#plt.subplot(num_img, 1, i+1)
plt.imshow(images[i])
#plt.imshow(images[i])
#plt.show()
def show_two_images(img1, img2, title1="Original Image", title2="Result Image"):
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(img1)
ax1.set_title(title1, fontsize=50)
ax2.imshow(img2)
ax2.set_title(title2, fontsize=50)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
def show_pair_images(images1, images2):
for i in range(len(images1)):
show_two_images(images1[i], imges2[i])
First, I'll compute the camera calibration using chessboard images
# a function that takes an image, object points, and image points
# performs the camera calibration, image distortion correction and
# returns the undistorted image
def cal_undistort(img, objpoints, imgpoints):
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
img_dst = cv2.undistort(img, mtx, dist, None, mtx)
return img_dst
def compute_camera_calibration(images,chessboard_size_x=9, chessboard_size_y=6):
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((chessboard_size_y*chessboard_size_x,3), np.float32)
objp[:,:2] = np.mgrid[0:chessboard_size_x,0:chessboard_size_y].T.reshape(-1,2)
# Arrays to store object points and image points from all the images.
objpoints = [] # 3d points in real world space
imgpoints = [] # 2d points in image plane.
# Make a list of calibration images
images_converted = []
# Step through the list and search for chessboard corners
for fname in images:
#print(fname)
img = cv2.imread(fname)
img_converted = np.copy(img)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Find the chessboard corners
ret, corners = cv2.findChessboardCorners(gray, (chessboard_size_x,chessboard_size_y),None)
# If found, add object points, image points
if ret == True:
objpoints.append(objp)
imgpoints.append(corners)
# Draw and display the corners
img_converted = cv2.drawChessboardCorners(img_converted, (chessboard_size_x,chessboard_size_y), corners, ret)
images_converted.append(img_converted)
# Undistort the original image using objpoints and imgpoints
img_undistorted = cal_undistort(img, objpoints, imgpoints)
show_two_images(img_converted, img_undistorted)
return objpoints, imgpoints
camera_images = glob.glob('./camera_cal/calibration*.jpg')
objpoints, imgpoints = compute_camera_calibration(camera_images)